package com.stgy.lease.common.utils;

import com.stgy.lease.common.exception.StgyException;
import com.stgy.lease.common.result.ResultCodeEnum;
import com.stgy.lease.model.domain.SystemUser;
import com.stgy.lease.model.domain.UserInfo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:JwtUtil
 * Package:com.stgy.lease.common.utils
 * Description:
 *
 * @Author:helei
 * @Create:2024/9/4 - 14:25
 */
public class JwtUtil {

    private static long tokenExpiration = 60 * 60 * 1000L;
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(SystemUser systemUser) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", systemUser.getId()).
                claim("name", systemUser.getName()).
                claim("avatar", systemUser.getAvatarUrl()).
                claim("ip", IpUtil.getIpAddress(requestAttributes.getRequest())).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }

    public static Map<String, Object> parseToken(String token, HttpServletRequest request) {
        try {
            String ipAddress = IpUtil.getIpAddress(request);
            Claims claims = JwtUtil.getPayLoad(token);
            String ip = claims.get("ip", String.class);
            if (!ipAddress.equals(ip)) {
                throw new StgyException(ResultCodeEnum.ILLEGAL_REQUEST);
            }
//            String avatar = claims.get("avatar", String.class);
//            String name = claims.get("name", String.class);
//            SystemUser systemUser = new SystemUser();
//            systemUser.setAvatarUrl(avatar);
//            systemUser.setName(name);
            return claims;
        } catch (ExpiredJwtException e) {
            throw new StgyException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new StgyException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static boolean checkToken(String token) {
        try {
            Claims body = Jwts.parserBuilder().
                    setSigningKey(tokenSignKey).
                    build().parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Claims getPayLoad(String token) {
        return Jwts.parserBuilder().
                setSigningKey(tokenSignKey).
                build().parseClaimsJws(token).getBody();
    }

    public static String createToken(UserInfo userInfo, HttpServletRequest request) {

        if (StringUtils.isEmpty(userInfo.getAvatarUrl())) {
            userInfo.setAvatarUrl("https://i0.hdslb.com/bfs/face/41703cc47175657261e088a1efb4906da542719e.jpg@92w_92h.avif");
        }
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userInfo.getId()).
                claim("name", userInfo.getNickname()).
                claim("avatar", userInfo.getAvatarUrl()).
                claim("ip", IpUtil.getIpAddress(request)).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }
}
